package com.winchain.chainbill.bill.biz.send.cmd;

import com.shell.bee.acct.transaction.po.AcctTxRec;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.file.service.PubFileService;
import com.shell.framework.command.CallbackContext;
import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICallback;
import com.shell.framework.command.ICommand;
import com.winchain.chainbill.bill.base.dao.CbAttDao;
import com.winchain.chainbill.bill.base.po.CbAtt;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.base.service.CbAttService;
import com.winchain.chainbill.bill.biz.Bill;
import com.winchain.chainbill.bill.biz.send.vo.BillAttInvoice;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillAttCmd<T> implements ICommand<Bill<T>>, ICallback<Bill<T>, AcctTxRec> {
	@Autowired
	private CbAttDao cbAttDao;
	@Autowired
	private PubFileService pubFileService;
	@Autowired
	private CbAttService cbAttService;

	public boolean execute(CommandContext<Bill<T>> context) throws Exception {
		CbRec record = ((Bill) context.getSource()).getRec();
		String bizId = (String) context.getValue("bizId");

		String contractFileIds = (String) context.getValue("contractFileIds");

		Object attInvoices = context.getValue("attInvoices");
		Object rejectFlag = context.getValue("rejectFlag");
		if (attInvoices != null) {
			String attInvoicesJson = attInvoices.toString();

			Map<List<String>, List<BillAttInvoice>> map = this.cbAttService.saveCbAtt(record.getBillId(), bizId,
					contractFileIds, attInvoicesJson, "4", "6");
			if ((StringUtil.notEmpty(attInvoicesJson)) && (map != null) && (map.size() > 0)) {
				List<BillAttInvoice> savecbAtts = (List) map.values().iterator().next();
				if ((savecbAtts != null) && (savecbAtts.size() > 0)) {
					context.setValue("saveAtts", savecbAtts);
				}
				List<String> invoiceNos = (List) map.keySet().iterator().next();
				if ((rejectFlag != null) && (((Boolean) rejectFlag).booleanValue())) {
					List<CbAtt> delCbAtts = this.cbAttDao.selectDelCbAtt(bizId, record.getBillId(), "6",
							(String[]) invoiceNos.toArray(new String[invoiceNos.size()]));
					if ((delCbAtts != null) && (delCbAtts.size() > 0)) {
						for (CbAtt delAtt : delCbAtts) {
							this.cbAttDao.deleteByPrimaryKey(delAtt.getAttId());
							this.pubFileService.clearRelateId(delAtt.getAttId(), "6");
						}
						context.setValue("delAtts", delCbAtts);
					}
				}
			}
		}
		return false;
	}

	public boolean callback(CallbackContext<Bill<T>, AcctTxRec> context) throws Exception {
		execute(context);
		return false;
	}
}
